package com.kulian.Signalling.system.service.impl.socket;

import com.kulian.Signalling.system.mode.socket.SignalingMessage;
import com.kulian.Signalling.system.service.impl.socket.handler.CallMessageHandler;
import com.kulian.Signalling.system.service.impl.socket.handler.MediaMessageHandler;
import com.kulian.Signalling.system.service.impl.socket.handler.RoomMessageHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class MessageHandlerFactory {
    private final RoomManager roomManager;
    private final MessageSender messageSender;
    
    private RoomMessageHandler roomMessageHandler;
    private CallMessageHandler callMessageHandler;
    private MediaMessageHandler mediaMessageHandler;

    public void handleMessage(SignalingMessage message, String username) {
        switch (SignalingMessage.MessageType.valueOf(message.getType())) {
            case CREATE_ROOM:
                getRoomHandler().handleCreateRoom(username);
                break;
            case JOIN_ROOM:
                getRoomHandler().handleJoinRoom(username, message.getRoomId());
                break;
            case LEAVE_ROOM:
                getRoomHandler().handleLeaveRoom(username);
                break;
            case CALL_REQUEST:
                getCallHandler().handleCallRequest(username, message.getTo(), message.getRoomId());
                break;
            case CALL_ACCEPT:
                getCallHandler().handleCallAccept(username, message.getTo(), message.getRoomId());
                break;
            case CALL_REJECT:
                getCallHandler().handleCallReject(username, message.getTo());
                break;
            case RINGING:
                getCallHandler().handleRinging(username, message.getTo());
                break;
            case HANGUP:
                getCallHandler().handleHangup(username, message.getTo(), message.getRoomId());
                break;
            case OFFER:
            case ANSWER:
            case ICE_CANDIDATE:
                getMediaHandler().forwardMediaMessage(username, message);
                break;
        }
    }

    private RoomMessageHandler getRoomHandler() {
        if (roomMessageHandler == null) {
            roomMessageHandler = new RoomMessageHandler(roomManager, messageSender);
        }
        return roomMessageHandler;
    }

    private CallMessageHandler getCallHandler() {
        if (callMessageHandler == null) {
            callMessageHandler = new CallMessageHandler(messageSender, roomManager);
        }
        return callMessageHandler;
    }

    private MediaMessageHandler getMediaHandler() {
        if (mediaMessageHandler == null) {
            mediaMessageHandler = new MediaMessageHandler(messageSender, roomManager);
        }
        return mediaMessageHandler;
    }
}
